package com.jiangyao.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.jiangyao.dao.IConfigDao;
import com.jiangyao.common.utils.StringUtils;
import com.jiangyao.model.entity.Config;
import com.jiangyao.service.ConfigService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 匹配表 服务实现类
 * </p>
 *
 * @author yych
 * @since 2019-10-16
 */
@Service
public class ConfigServiceImpl extends ServiceImpl<IConfigDao, Config> implements ConfigService {

	private Map<String, String> configCacheMap;

	@Autowired
	private IConfigDao configDao;

	/**
	 * 获取单个配置项
	 *
	 * @param code
	 * @return
	 */
	@Override
	public String getValue(String code) {
		QueryWrapper<Config> queryWrapper = new QueryWrapper<>();
		queryWrapper.eq("code", code);

		Config config = configDao.selectOne(queryWrapper);

		if (config != null) {
			return config.getValue();
		}

		return "";
	}

	/**
	 * 获取单个配置项(缓存)
	 *
	 * @param code 配置code
	 * @return 结果
	 */
	@Override
	public String getValueFromCache(String code) {
		if (StringUtils.isBlank(code)) {
			return null;
		}

		if (configCacheMap == null) {
			initConfigCacheMap();
		}
		return configCacheMap.get(code);
	}


	/**
	 * 初始化配置
	 * 10分钟刷新一次
	 */
	@Scheduled(cron = "0 0/10 * * * ? ")
	@Override
	public void initConfigCacheMap() {
		synchronized (configDao) {
			configCacheMap = new HashMap<>();
			List<Config> configList = configDao.selectList(null);
			if (configList == null || configList.isEmpty()) {
				return;
			}
			configList.forEach(config -> configCacheMap.put(config.getCode(), config.getValue()));
		}
	}
}